# D:\dazuoye\app\views\sales_customer.py

from flask import Blueprint, jsonify
from app.data_loader import customer_purchase_data
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import pandas as pd

customer_bp = Blueprint('sales_customer', __name__)


@customer_bp.route('/api/sales/customer_segments', methods=['GET'])
def get_customer_segments():
    """API: 客户分群聚类图 (使用K-Means)"""
    if customer_purchase_data is None:
        return jsonify({"error": "客户购买数据未能加载"}), 500

    try:
        df = customer_purchase_data.copy()

        features = ['客户终身价值', '平均订单价值', '购买频率(天)']
        df_cluster = df[features].dropna()

        scaler = StandardScaler()
        features_scaled = scaler.fit_transform(df_cluster)

        kmeans = KMeans(n_clusters=4, random_state=42, n_init=10)
        clusters = kmeans.fit_predict(features_scaled)

        df_cluster['cluster'] = clusters

        result = []
        for index, row in df_cluster.iterrows():
            result.append({
                "x": int(row['购买频率(天)']),
                "y": float(row['客户终身价值']),
                "z": float(row['平均订单价值']),
                "cluster": int(row['cluster']),
                "name": f"客户群-{int(row['cluster'])}"
            })

        return jsonify(result)

    except Exception as e:
        return jsonify({"error": f"客户分群时出错: {e}"}), 500


@customer_bp.route('/api/sales/frequency_aov', methods=['GET'])
def get_frequency_aov():
    """API: 购买频率与客单价关系图"""
    if customer_purchase_data is None:
        return jsonify({"error": "客户购买数据未能加载"}), 500

    df = customer_purchase_data[['购买频率(天)', '平均订单价值']].dropna()

    df['购买频率(天)'] = df['购买频率(天)'].astype(int)
    df['平均订单价值'] = df['平均订单价值'].astype(float)

    # 【修正点】补全缺失的引号和括号
    result = df.to_dict(orient='records')

    return jsonify(result)